package com.example.courseapp.activity;

import static com.example.courseapp.utils.BigDecimalUtils.toFixed;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.table.TableData;
import com.example.courseapp.R;
import com.example.courseapp.RetrofitHelper;
import com.example.courseapp.bean.AnalyzePojo;
import com.example.courseapp.bean.ChildInformation;
import com.example.courseapp.bean.ChildInformationHis;
import com.example.courseapp.bean.ChildSportRecords;
import com.example.courseapp.bean.FoodRemVo;
import com.example.courseapp.bean.SportRem;
import com.example.courseapp.bean.HealthAnalyze;
import com.example.courseapp.bean.LayerInfoTableView;
import com.example.courseapp.net.CourseService;
import com.example.courseapp.utils.DimenUtils;
import com.github.mikephil.charting.charts.LineChart;
//import com.lingber.mycontrol.datagridview.DataGridView;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RecordActivity2 extends AppCompatActivity {

    List<String> foodL = new ArrayList<>();

    TextView myContent;
    TextView myContent1, tv_DietSuggestion, sportRemTV;
    ImageView iv_DietSuggestion;
    TextView analyzeResult;
    CourseService service;
    TableLayout table_head, table_content;

    private LayerInfoTableView tableView;

    ChildInformation childInformation;
    Integer childID;

    LineChart lineChart;
    SmartTable table;

    //    DataGridView mDataGridView = findViewById(R.id.datagridview);
    ChildInformation child;
    ArrayList<ChildInformationHis> childInformationHisList = new ArrayList<>();
    ArrayList<ChildInformationHis> tempChildInformationHisList = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_record2);

        lineChart = findViewById(R.id.linechart);


        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.back).setOnClickListener(v -> {
            finish();
        });

        myContent = findViewById(R.id.myContent);
        table = findViewById(R.id.table);
        myContent1 = findViewById(R.id.myContent1);
        tv_DietSuggestion = findViewById(R.id.tv_DietSuggestion);
        sportRemTV = findViewById(R.id.sportRemTV);
        iv_DietSuggestion = findViewById(R.id.iv_DietSuggestion);
        analyzeResult = findViewById(R.id.analyzeResult);
        table_head = findViewById(R.id.table_head);
        table_content = findViewById(R.id.table_content);


        service = RetrofitHelper.getInstance().createService(CourseService.class);
        childID = getIntent().getIntExtra("childID", 0);
        service.getChildHis().enqueue(new Callback<List<ChildInformationHis>>() {
            @Override
            public void onResponse(Call<List<ChildInformationHis>> call, Response<List<ChildInformationHis>> response) {
                Log.d("getChilehis", response.body().get(0).toString());
                for (int i = 0; i < response.body().size(); i++) {
                    childInformationHisList.add(response.body().get(i));
                    int id = childID;
                    int nowChildId = Math.toIntExact(response.body().get(i).getChildId());
                    Log.d("id and nowChildId:", id + " " + nowChildId);
                    if (nowChildId == id) {
                        tempChildInformationHisList.add(response.body().get(i));
                    }
                }
                service.getChildById(childID).enqueue(new Callback<ChildInformation>() {
                    @Override
                    public void onResponse(Call<ChildInformation> call, Response<ChildInformation> response) {
                        child = response.body();
                        initTable();

                        Double BMI = 0.0;
                        Double nowBMI = 0.0;
                        if (tempChildInformationHisList.isEmpty()) {
                            nowBMI = Double.parseDouble(child.getBmi());
                        }
                        else {
                            BMI = tempChildInformationHisList.get(tempChildInformationHisList.size() - 1).getBmi();
                            nowBMI = Double.parseDouble(child.getBmi());
                        }

                        getFoodRemByBmi(nowBMI);
                        getSportRemByBmi(nowBMI);
                        getAnalyze(BMI, nowBMI);
                    }

                    @Override
                    public void onFailure(Call<ChildInformation> call, Throwable t) {

                    }
                });
            }

            @Override
            public void onFailure(Call<List<ChildInformationHis>> call, Throwable t) {

            }
        });


    }

    private void refreshData() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                refreshInUiThread();
            }
        }, 5000, 1000);
    }

    private void refreshInUiThread() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                System.out.println("-------延迟5000毫秒，每1000毫秒执行一次--------");
//                tableView.setData(new IeNr5gBin());
            }
        });
    }

    private void initTable() {
        Column column1 = new Column<String>("日期", "createTime");
        Column column2 = new Column<Double>("身高", "height");
        Column column3 = new Column<Double>("体重", "weight");
        Column column4 = new Column<Double>("BMI", "bmi");
        ArrayList<Column> columns = new ArrayList<>();
        columns.add(column1);
        columns.add(column2);
        columns.add(column3);
        columns.add(column4);
        ArrayList<ChildInformationHis> list = new ArrayList<>();
        list.addAll(tempChildInformationHisList);
        list.add(new ChildInformationHis(child.getChildID().longValue(), new Double(child.getHeight()), new Double(child.getWeight()), child.getAge(), new Double(child.getBmi()), ""));
        ViewGroup.LayoutParams layoutParams = table.getLayoutParams();
        layoutParams.height = (list.size() + 2) * DimenUtils.dpToPx(this, 40);
        table.setLayoutParams(layoutParams);
        TableData<ChildInformationHis> data = new TableData<>("基本数据", list, columns);
        table.setTableData(data);
    }

    public static List<ChildSportRecords> filterLastSevenDays(List<ChildSportRecords> dateList) {
        List<ChildSportRecords> lastSevenDays = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        for (ChildSportRecords dateStr : dateList) {
            // 将日期字符串解析成LocalDate对象
            LocalDate date = LocalDate.parse(dateStr.getCreateTime().split(" ")[0], formatter);

            // 检查日期是否在近七天内
            if (date.isAfter(currentDate.minusDays(7)) && date.isBefore(currentDate.plusDays(1))) {
                lastSevenDays.add(dateStr);
            }
        }

        return lastSevenDays;
    }


    private static String suggest1 = "体重偏轻可能与饮食结构不合理有关，建议患者适当调整饮食结构，多吃富含蛋白质、维生素的食物，如鸡蛋、芹菜等，有助于补充机体所需要的营养物质，改善体重偏轻的情况.";

    public static String validateBMI(double weight, double height) {
        // 计算BMI
        double bmi = weight / (height / 100 * height / 100);

        DecimalFormat decimalFormat = new DecimalFormat("#.#");

        // 使用 DecimalFormat 格式化 float 值
        String formattedValue = decimalFormat.format(bmi);
        // 根据BMI范围进行判断
        if (bmi < 18.5) {
            return "当前BMI为" + formattedValue + "通过BMI判断：体重过轻";
        } else if (bmi >= 18.5 && bmi < 24.9) {
            return "当前BMI为" + formattedValue + "通过BMI判断：正常体重";
        } else if (bmi >= 25 && bmi < 29.9) {
            return "当前BMI为" + formattedValue + "通过BMI判断：超重";
        } else {
            return "当前BMI为" + formattedValue + "通过BMI判断：肥胖";
        }
    }


    public static String getBMI(double weight, double height) {
        // 计算BMI
        double bmi = weight / (height / 100 * height / 100);
        return toFixed(bmi, 0);
    }

    public static String validateExerciseDuration(int age, double weeklyExerciseHours) {
        // 根据世界卫生组织的建议，给出相应年龄段的合理运动时长
        int recommendedHours;

        if (age >= 3 && age <= 4) {
            recommendedHours = 3 * 7;  // 幼儿每天至少3小时
        } else if (age >= 5 && age <= 17) {
            recommendedHours = 1 * 7;  // 5-17岁儿童每天至少1小时
        } else {
            return "年龄不在建议范围（3~17岁）内";
        }

        // 判断实际运动时长是否符合建议
        if (weeklyExerciseHours >= recommendedHours) {
            return "运动时长符合建议";
        } else {
            return "运动时长不足，建议增加运动时间";
        }
    }

    public static String recommendExercise(int age) {
        if (age >= 3 && age <= 6) {
            return "适合的运动方案：户外游戏、舞蹈、游泳、亲子体育活动。";
        } else if (age >= 7 && age <= 12) {
            return "适合的运动方案：球类运动、体操、自行车骑行、轻度力量训练。";
        } else if (age >= 13 && age <= 17) {
            return "适合的运动方案：跑步和慢跑、团体运动、游泳、青少年瑜伽、个性化运动。";
        } else {
            return "年龄不在建议范围（3~17岁）内";
        }
    }

    public void getAnalyze(double lastBmi, double nowBmi) {
        service.analyze(new AnalyzePojo(lastBmi, nowBmi)).enqueue(new Callback<HealthAnalyze>() {
            @Override
            public void onResponse(Call<HealthAnalyze> call, Response<HealthAnalyze> response) {
                try {
                    HealthAnalyze body = response.body();
                    if (body != null) {
                        Log.e("RecordActivity2", "onResponse: " + body.getAnalysizeContent());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String content = body.getAnalysizeContent();
                                if (content == null || content.isEmpty()) {
                                    analyzeResult.setText("暂无具体分析，敬请期待~");
                                } else {
                                    analyzeResult.setText(content);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    analyzeResult.setText("暂无具体分析，敬请期待~");
                }
            }

            @Override
            public void onFailure(Call<HealthAnalyze> call, Throwable t) {
                Log.e("RecordActivity2", "onFailure: 请求失败" );
            }
        });
    }

    public void getFoodRemByBmi(double bmi) {
        service.getFoodRemByBmi(bmi).enqueue(new Callback<FoodRemVo>() {
            @Override
            public void onResponse(Call<FoodRemVo> call, Response<FoodRemVo> response) {
                try {
                    FoodRemVo body = response.body();
                    if (body != null) {
                        Log.e("RecordActivity2", "onResponse: getFoodRemByBmi 请求成功 " + body.getFoodGuide());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String foodGuide = body.getFoodGuide();
                                if (foodGuide == null || foodGuide.isEmpty()) {
                                    tv_DietSuggestion.setText("暂无饮食指导，敬请期待~");
                                } else {
                                    tv_DietSuggestion.setText(foodGuide);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    tv_DietSuggestion.setText("暂无饮食指导，敬请期待~");
                }
            }

            @Override
            public void onFailure(Call<FoodRemVo> call, Throwable t) {
                Log.e("RecordActivity2", "onFailure: getFoodRemByBmi 请求失败");
            }
        });
    }

    public void getSportRemByBmi(double bmi) {
        service.getSportRemByBmi(bmi).enqueue(new Callback<SportRem>() {
            @Override
            public void onResponse(Call<SportRem> call, Response<SportRem> response) {
                try {
                    SportRem body = response.body();
                    if (body != null) {
                        Log.e("RecordActivity2", "onResponse: getSportRemByBmi 请求成功 " + body.getSportContent());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                sportRemTV.setText(body.getSportContent());
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sportRemTV.setText("暂无运动指导，敬请期待~");
                        }
                    });
                }
            }

            @Override
            public void onFailure(Call<SportRem> call, Throwable t) {
                Log.e("RecordActivity2", "onFailure: getSportRemByBmi 请求失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        sportRemTV.setText("暂无运动指导，敬请期待~");
                    }
                });
            }
        });
    }
}